<template>
  <!-- 条件查询 -->
     <el-form :inline="true" :model="formInline" class="demo-form-inline">
    <el-form-item label="编号">
      <el-input v-model="formInline.Customer_Number" placeholder="请输入编号" clearable />
    </el-form-item>
     <el-form-item label="客户名称">
      <el-input v-model="formInline.Customer_Name" placeholder="请输入客户名称" clearable />
    </el-form-item>
     <el-form-item label="电话">
      <el-input v-model="formInline.Phone" placeholder="请输入电话" clearable />
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="getdata()">查询</el-button>
    </el-form-item>
  </el-form>


   <!-- 页面数据 -->
  <el-button plain @click="AddWarehouse()">
新增
  </el-button>
     <el-button plain @click="handleExport()">
导出
  </el-button>
  
 <el-table :data="tableData" style="width: 100%">
  <el-table-column prop="customer_Number" label="客户编号" width="100" />
    <el-table-column prop="customer_Name" label="客户名称" width="100"  />
    <el-table-column prop="phone" label="电话" width="100" />
    <el-table-column prop="fax" label="传真" width="100" />
    <el-table-column prop="email" label="邮箱" width="100" />
    <el-table-column prop="contacts" label="联系人" width="100" />
    <el-table-column prop="address" label="地址" width="100" />
    <el-table-column prop="createTime" label="创建时间" width="100" >
      <template v-slot="scoped">
      {{formatDate(scoped.row.createTime)}}
      </template>
    </el-table-column>
     <el-table-column fixed="right" label="操作" width="250">
      <template #default="scoped">
        <el-button type="primary" @click="UpdateWarehouse(scoped.row)">编辑</el-button>
      <el-button type="danger" @click="del(scoped.row.id)">删除</el-button>
      </template>
    </el-table-column>
  </el-table>

  <!-- 分页 -->
    <el-pagination
      v-model:current-page="page.PageIndex"
      v-model:page-size="page.PageSize"
      :page-sizes="[15, 20, 25, 30]"
      layout="total, sizes, prev, pager, next, jumper"
      prev-text="上一页"
      next-text="下一页"
      :total="page.totalCount"
    />

    <!-- 客户新增弹窗 -->
<el-dialog
    v-model="dialogVisible"
    title="新增客户"
    width="800"
  >
 <el-form
    ref="ruleFormRef"
    style="max-width: 700px"
    :model="ruleForm"
    :rules="rules"
    label-width="auto"
  >
    <!-- 客户基本信息 -->
    <div style="display: flex; gap: 20px;">
      <div style="flex: 1;">
        <el-form-item label="客户编号" prop="">
          <el-input v-model="ruleForm.customer_Number" disabled/>
        </el-form-item>
        
        <el-form-item label="客户名称" prop="">
          <el-input v-model="ruleForm.customer_Name" />
        </el-form-item>
        <el-form-item label="电话" prop="">
          <el-input v-model="ruleForm.phone" />
        </el-form-item>
      </div>
      
      <div style="flex: 1;">
        <el-form-item label="传真" prop="">
          <el-input v-model="ruleForm.fax" />
        </el-form-item>

        <el-form-item label="邮箱" prop="">
          <el-input v-model="ruleForm.email" />
        </el-form-item>

        <el-form-item label="备注" prop="">
          <el-input v-model="ruleForm.notes" />
        </el-form-item>
      </div>
    </div>

    <!-- 联系人表格 -->
    <div style="margin-top: 20px;">
      <h4>联系人信息</h4>
      <el-table :data="contactsList" style="width: 100%">
        <el-table-column prop="contacts" label="联系人" width="120">
          <template #default="scope">
            <el-input v-model="scope.row.contacts" placeholder="请输入" v-if="scope.row.isEdit" />
            <span v-else>{{ scope.row.contacts }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="address" label="地址" width="150">
          <template #default="scope">
            <el-input v-model="scope.row.address" placeholder="请输入" v-if="scope.row.isEdit" />
            <span v-else>{{ scope.row.address }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="contacts_Phone" label="电话" width="120">
          <template #default="scope">
            <el-input v-model="scope.row.contacts_Phone" placeholder="请输入" v-if="scope.row.isEdit" />
            <span v-else>{{ scope.row.contacts_Phone }}</span>
          </template>
        </el-table-column>
   
        <el-table-column label="操作" width="120">
          <template #default="scope">
            <el-button 
              type="primary" 
              link 
              @click="editContact(scope.$index)"
              v-if="!scope.row.isEdit && scope.row.contacts && scope.row.address && scope.row.contacts_Phone"
            >
              编辑
            </el-button>
            <el-button 
              type="danger" 
              link 
              @click="deleteContact(scope.$index)"
              v-if="!scope.row.isEdit && scope.row.contacts && scope.row.address && scope.row.contacts_Phone"
            >
              删除
            </el-button>
            <el-button 
              type="primary" 
              link 
              @click="saveContact(scope.$index)"
              v-if="scope.row.isEdit"
            >
              保存
            </el-button>
            <el-button 
              type="danger" 
              link 
              @click="cancelContact(scope.$index)"
              v-if="scope.row.isEdit"
            >
              取消
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <el-button type="primary" @click="addNewContact" style="margin-top: 10px;">
        添加联系人
      </el-button>
    </div>

    <el-form-item style="margin-top: 20px;">
      <el-button @click="dialogVisible = false">取消</el-button>
      <el-button type="primary" @click="submitForm(ruleFormRef)">
        确定
      </el-button>
    </el-form-item>
  </el-form>

  </el-dialog>

  <!-- 编辑弹窗 -->
<el-dialog
    v-model="updialogVisible"
    title="编辑客户"
    width="800"
  >
 <el-form
    ref="ruleFormRef"
    style="max-width: 700px"
    :model="ruleForm"
    :rules="rules"
    label-width="auto"
  >
    <!-- 客户基本信息 -->
    <div style="display: flex; gap: 20px;">
      <div style="flex: 1;">
        <el-form-item label="客户编号" prop="">
          <el-input v-model="ruleForm.customer_Number" disabled/>
        </el-form-item>
        
        <el-form-item label="客户名称" prop="">
          <el-input v-model="ruleForm.customer_Name" />
        </el-form-item>
        <el-form-item label="电话" prop="">
          <el-input v-model="ruleForm.phone" />
        </el-form-item>
      </div>
      
      <div style="flex: 1;">
        <el-form-item label="传真" prop="">
          <el-input v-model="ruleForm.fax" />
        </el-form-item>

        <el-form-item label="邮箱" prop="">
          <el-input v-model="ruleForm.email" />
        </el-form-item>

        <el-form-item label="备注" prop="">
          <el-input v-model="ruleForm.notes" />
        </el-form-item>
      </div>
    </div>

    <!-- 联系人表格 -->
    <div style="margin-top: 20px;">
      <h4>联系人信息</h4>
      <el-table :data="contactsList" style="width: 100%">
        <el-table-column prop="contacts" label="联系人" width="120">
          <template #default="scope">
            <el-input v-model="scope.row.contacts" placeholder="请输入" v-if="scope.row.isEdit" />
            <span v-else>{{ scope.row.contacts }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="address" label="地址" width="150">
          <template #default="scope">
            <el-input v-model="scope.row.address" placeholder="请输入" v-if="scope.row.isEdit" />
            <span v-else>{{ scope.row.address }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="contacts_Phone" label="电话" width="120">
          <template #default="scope">
            <el-input v-model="scope.row.contacts_Phone" placeholder="请输入" v-if="scope.row.isEdit" />
            <span v-else>{{ scope.row.contacts_Phone }}</span>
          </template>
        </el-table-column>
   
        <el-table-column label="操作" width="120">
          <template #default="scope">
            <el-button 
              type="primary" 
              link 
              @click="editContact(scope.$index)"
              v-if="!scope.row.isEdit && scope.row.contacts && scope.row.address && scope.row.contacts_Phone"
            >
              编辑
            </el-button>
            <el-button 
              type="danger" 
              link 
              @click="deleteContact(scope.$index)"
              v-if="!scope.row.isEdit && scope.row.contacts && scope.row.address && scope.row.contacts_Phone"
            >
              删除
            </el-button>
            <el-button 
              type="primary" 
              link 
              @click="saveContact(scope.$index)"
              v-if="scope.row.isEdit"
            >
              保存
            </el-button>
            <el-button 
              type="danger" 
              link 
              @click="cancelContact(scope.$index)"
              v-if="scope.row.isEdit"
            >
              取消
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <el-button type="primary" @click="addNewContact" style="margin-top: 10px;">
        添加联系人
      </el-button>
    </div>

    <el-form-item style="margin-top: 20px;">
      <el-button @click="updialogVisible = false">取消</el-button>
      <el-button type="primary" @click="updatesubmitForm(ruleFormRef)" :disabled="!canConfirmEdit">
        确定
      </el-button>
    </el-form-item>
  </el-form>

  </el-dialog>

</template>

<script setup lang="ts">
import axios from 'axios'
import { reactive,onMounted, ref, watch, computed } from 'vue'
import { BasicsRed } from '@/http/axiosHelper'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useRouter } from 'vue-router'
import { BasicsWrite } from '@/http/axiosHelper'
import { statementRed } from '@/http/axiosHelper'
const router=useRouter();
const dialogVisible = ref(false)
const updialogVisible = ref(false)

function formatDate(dateStr: string) {
  if (!dateStr) return '';
  const date = new Date(dateStr);
  if (isNaN(date.getTime())) return dateStr;
  const y = date.getFullYear();
  const m = String(date.getMonth() + 1).padStart(2, '0');
  const d = String(date.getDate()).padStart(2, '0');
  return `${y}-${m}-${d}`;
}

  
const AddWarehouse=()=>
{
   dialogVisible.value=true;
     ruleForm.customer_Number= generateDateBasedNumber(),
  ruleForm.customer_Name= "",
  ruleForm.notes= "",
  ruleForm.fax="",
  ruleForm.email="",
  ruleForm.phone=""
   // 重置联系人列表为初始状态
   contactsList.value = [
     {
       contacts: "",
       address: "",
       contacts_Phone: "",
      
       isEdit: false
     },
    // {
    //    contacts: "王聪",
    //    address: "合作供应商", 
    //    contacts_Phone: "05694482",
    //    createTime: "2019-05-29",
    //    isEdit: false
    //  }
   ]
}

const UpdateWarehouse=(row:any)=>
{
   Object.assign(ruleForm,row);
   updialogVisible.value=true
   
   // 加载联系人数据
   loadCustomerContacts(row.customer_Number)
}

// 加载客户联系人数据
const loadCustomerContacts = (id: any) => {
  // 尝试调用API获取联系人数据
  BasicsRed.get("/api/Customer/FanCustomerHandle", { params: { customer_Number: id } }).then(res => {
    if (res.data.code === 200 && res.data.data) {
      contactsList.value = res.data.data.map((contact: any) => ({
        ...contact,
        isEdit: false
      }))
    } else {
      // 如果没有数据，清空列表
      contactsList.value = []
    }
  }).catch(() => {
    // 如果API不存在或出错，清空联系人列表
    console.log('获取联系人API不存在或出错，清空联系人列表')
    contactsList.value = []
  })
}

const updatesubmitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      // 准备提交数据，包含联系人信息
      const submitData = {
        customer: {
          ...ruleForm
        },
        contacts: contactsList.value.filter(item => item.contacts && item.address && item.contacts_Phone)
      }
   BasicsWrite.post("/api/Customer/UpdateCustomerHandle",submitData).then(res=>
    {
        if(res.data.code==200)
    {
        ElMessage.success(res.data.msg);
  updialogVisible.value=false;
     getdata()
    }
    else
    {
            ElMessage.success(res.data.msg);
    }
    }
   )
    }
  })
}


// 改进版 - 添加持久化支持
const generateDateBasedNumber = (incrementLength: number = 4) => {
  const now = new Date();
  const datePart = `${now.getFullYear()}${String(now.getMonth() + 1).padStart(2, '0')}${String(now.getDate()).padStart(2, '0')}`;
  
  // 从localStorage读取或初始化计数器
  const storageKey = `dateNumCounter_${datePart}`;
  let currentCount = localStorage.getItem(storageKey);
  
  // 如果localStorage中没有值，则初始化为0
  if (currentCount === null) {
    currentCount = '0';
  }
  
  // 转换为数字，递增，然后转回字符串
  const numericCount = parseInt(currentCount, 10) + 1;
  currentCount = numericCount.toString();
  
  // 保存新的计数器值
  localStorage.setItem(storageKey, currentCount);

  // 确保incrementLength是数字，然后生成递增部分
  const incrementPart = currentCount.padStart(incrementLength, '0');
  
  return datePart + incrementPart;
};

import {  type FormInstance, type FormRules } from 'element-plus'
const ruleFormRef = ref<FormInstance>()
const ruleForm = reactive({
  id:0,
 "customer_Number": generateDateBasedNumber(),
    "customer_Name": "",
    "fax": "",
    "email": "",
    "phone": "",
    "notes": ""
})
const ruleFormss = reactive({
   "contacts": "",
      "address": "",
      "contacts_Phone": ""
})

// 联系人列表
const contactsList = ref([
  {
    contacts: "",
    address: "",
    contacts_Phone: "",
    isEdit: false
  }
  // {
  //   contacts: "王聪",
  //   address: "合作供应商", 
  //   contacts_Phone: "05694482",
  //   createTime: "2019-05-29",
  //   isEdit: false
  // }
])

// 添加新联系人
const addNewContact = () => {
  contactsList.value.push({
    contacts: "",
    address: "",
    contacts_Phone: "",
    isEdit: true
  })
}

// 编辑联系人
const editContact = (index: number) => {
  contactsList.value[index].isEdit = true
}

// 保存联系人
const saveContact = (index: number) => {
  contactsList.value[index].isEdit = false
}

// 删除联系人
const deleteContact = (index: number) => {
  contactsList.value.splice(index, 1)
}

// 取消新增联系人
const cancelContact = (index: number) => {
  // 如果联系人信息为空，则删除这一行
  const contact = contactsList.value[index]
  if (!contact.contacts && !contact.address && !contact.contacts_Phone) {
    contactsList.value.splice(index, 1)
  } else {
    // 如果有数据，则退出编辑模式
    contact.isEdit = false
  }
}

const locationOptions = ['Home', 'Company', 'School']

const rules = reactive<FormRules>({
  name: [
    { required: true, message: 'Please input Activity name', trigger: 'blur' },
    { min: 3, max: 5, message: 'Length should be 3 to 5', trigger: 'blur' },
  ],
  region: [
    {
      required: true,
      message: 'Please select Activity zone',
      trigger: 'change',
    },
  ],
  count: [
    {
      required: true,
      message: 'Please select Activity count',
      trigger: 'change',
    },
  ],
  date1: [
    {
      type: 'date',
      required: true,
      message: 'Please pick a date',
      trigger: 'change',
    },
  ],
  date2: [
    {
      type: 'date',
      required: true,
      message: 'Please pick a time',
      trigger: 'change',
    },
  ],
  location: [
    {
      required: true,
      message: 'Please select a location',
      trigger: 'change',
    },
  ],
  type: [
    {
      type: 'array',
      required: true,
      message: 'Please select at least one activity type',
      trigger: 'change',
    },
  ],
  resource: [
    {
      required: true,
      message: 'Please select activity resource',
      trigger: 'change',
    },
  ],
  desc: [
    { required: true, message: 'Please input activity form', trigger: 'blur' },
  ],
})

const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      // 准备提交数据，包含联系人信息
      const submitData = {
        customer: {
          ...ruleForm
        },
        contacts: contactsList.value.filter(item => item.contacts && item.address && item.contacts_Phone)
      }
      
   BasicsWrite.post("/api/Customer/CreateCustomerHandle",submitData).then(res=>
    {
        if(res.data.code==200)
    {
        ElMessage.success(res.data.msg);

       
     ruleForm.customer_Number= generateDateBasedNumber(),
  ruleForm.customer_Name= "",
  ruleForm.notes= "",
  ruleForm.fax="",
  ruleForm.email="",
  ruleForm.phone=""
  
  // 清空联系人列表
  contactsList.value = []

  dialogVisible.value=false;
getdata()
    }
    else
    {
            ElMessage.success(res.data.msg);
    }
    }
   )
    }
  })
}

const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
}

const options = Array.from({ length: 10000 }).map((_, idx) => ({
  value: `${idx + 1}`,
  label: `${idx + 1}`,
}))

const handleClose = (done: () => void) => {
  ElMessageBox.confirm('Are you sure to close this dialog?')
    .then(() => {
      done()
    })
    .catch(() => {
      // catch error
    })
}



const formInline = reactive({

  Customer_Number: '',
  Customer_Name: '',
  Phone: '',

})
const page=reactive({
    PageIndex:1,
    PageSize:15,
    totalCount:0

})
watch(page,()=>
{
  getdata();
})
onMounted(()=>
{
    
    getdata();
})


const del=(id:any)=>
{

ElMessageBox.confirm(
    '确认删除吗?',
    '提示',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(() => {
     BasicsWrite.put("/api/Customer/DelCustomerHandle",{id:id}).then(res=>
{
   if(res.data.code==200)
   {
    ElMessage.success("删除成功");
    getdata();
   }
   else
   {
    ElMessage.success("删除失败");
   }
}
)
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '已取消',
      })
    })




}

const deplarment=ref()
const delparmentdata=(id:any)=>
{
    BasicsRed.get("/api/Customer/FanCustomerHandle",{params:{id:id}}).then(res=>
        {
            deplarment.value=res.data.data
        }
    )
}

const tableData : any=ref([]);

const getdata=()=>
{
    BasicsRed.get("/api/Customer/GetCustomerHandle",{params:{
      PageIndex:page.PageIndex,
      PageSize:page.PageSize,
      Customer_Name:formInline.Customer_Name,
      Customer_Number:formInline.Customer_Number,
      Phone:formInline.Phone
    
    
    }}).then(res=>
        {
tableData.value=res.data.data
page.totalCount=res.data.totalCount
        }
    )
}

// 导出函数（假设已配置 Axios 拦截器自动添加 Token）
async function handleExport() {
    try {
        // 1. 调用后端导出接口（GET 请求，参数通过 params 传递）
        const response = await BasicsRed({
            url: '/api/Customer/GetCustomerExport', // 后端接口地址
            method: 'GET',
            params: {
                  PageIndex:page.PageIndex,
                  PageSize:page.PageSize,
                  Customer_Name:formInline.Customer_Name,
                  Customer_Number:formInline.Customer_Number,
                  Phone:formInline.Phone
            }, // 对应后端 [FromQuery] 的 command 参数
            responseType: 'blob', // 关键：指定响应类型为二进制流（Excel 文件）
        });

        // 2. 从响应头获取文件名（后端通过 File 方法设置的 fileName）
        const fileName = getFileNameFromHeaders(response.headers);

        // 3. 生成下载链接并触发下载
        const blob = new Blob([response.data], {
            type: response.headers['content-type'] || 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
        });
        const url = window.URL.createObjectURL(blob);
        const a = document.createElement('a');
        a.href = url;
        a.download = fileName; // 文件名从响应头获取或自定义
        document.body.appendChild(a);
        a.click();

        // 4. 清理资源
        window.URL.revokeObjectURL(url);
        document.body.removeChild(a);

    } catch (error: any) {
        // 处理错误（如后端返回 401/400 等）
        console.error('导出失败：', error.response?.data || error.message);
        alert('导出失败，请检查参数或重新登录');
    }
}


// 辅助函数：从响应头提取文件名（后端通过 File 方法设置）
function getFileNameFromHeaders(headers: any) {
    const contentDisposition = headers['content-disposition'] || headers['Content-Disposition'];
    if (!contentDisposition) return '客户管理.xlsx'; // 默认文件名

    // 解码文件名（处理中文编码问题）
    const match = contentDisposition.match(/filename\*?=([^;]+)/);
    if (match) {
        return decodeURIComponent(match[1].replace(/["']/g, ''));
    }
    return '客户管理.xlsx';
}


const onSubmit = () => {
  console.log('submit!')
}

const canConfirmEdit = computed(() => {
  // 没有正在编辑的联系人
  const allSaved = contactsList.value.every(item => !item.isEdit)
  // 所有联系人信息都填写完整
  const allFilled = contactsList.value.every(
    item => item.contacts && item.address && item.contacts_Phone
  )
  // 至少有一个联系人
  const hasContact = contactsList.value.length > 0
  return allSaved && allFilled && hasContact
})
</script>

<style scoped>
.demo-form-inline .el-input {
  --el-input-width: 120px;
}

.demo-form-inline .el-select {
  --el-select-width: 120px;
}
</style>